package com.example.listening.examsdk.core;

import android.text.TextUtils;

import com.example.listening.examsdk.ExamSDK;
import com.example.listening.utils.Logger;

import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by tong on 15/11/18.
 * 课程信息
 */
public class Lesson implements Serializable {
    public static final String ID_PERFIX = "Lesson";

    /**
     * 宿主文件相对路径
     */
    private String location;

    /**
     * 在父节点的id
     */
    private String id;

    /**
     * 在父节点的索引
     */
    private final int position;


    /**
     * 课程名字
     */
    private String name;

    /**
     * 测试时间，单位秒
     */
    private int testTime;

    /**
     * 及格分数
     */
    private int passScore;

    /**
     * 题目总数量
     */
    private int numQ;

    /**
     * 难度
     */
    private Difficulty difficulty;

    /**
     * 子题目
     */
    private List<Section> sections = new ArrayList<Section>();

    private List<String> qList = new ArrayList<String>();

    private List<Subject> subjects;

    public Lesson(String location, String lessonId, JSONObject lessonObj) {
//        "Lesson1": {
//            "Head": {
//                "Name": "初一英语听力基础1",
//                        "About": "",
//                        "NumQ": "22",
//                        "TestTime": "20",
//                        "PassScore": "60",
//                        "Difficulty": "4"
//            },
//            "Body": {
//                "Section_A": {
//                    "Txt": "听对话,从下面各题所给的A、B、C三幅图片中选择与对话内容相符的图片。每段对话读两遍",
//                            "Sound": "Z1_A.mp3",
//                            "Q1": "Q21_1_1_000011",
//                            "Q2": "Q21_1_1_000012",
//                            "Q3": "Q21_1_1_000013",
//                            "Q4": "Q21_1_1_000014",
//                            "Q5": "Q21_1_1_000015"
//                },
//                "Section B": {
//                    "Txt": "听对话或独白,根据对话或独白的内容,从下面各题所给的A、B、C三个选项中选择最佳选项。每段对话或独白读两遍",
//                            "Sound": "Z1_B.mp3",
//                            "Q1": "Q21_1_2_000021",
//                            "Q2": "Q21_1_2_000022",
//                            "Q3": "Q21_1_2_000023",
//                            "Q4": "Q21_1_2_000024",
//                            "Q5": "Q21_1_2_000025",
//                            "Q6": "Q21_1_2_000026",
//                            "Q7": "Q21_1_2_000027",
//                            "Q8": "Q21_1_2_000028",
//                            "Q9": "Q21_1_2_000029",
//                            "Q10": "Q21_1_2_000030",
//                            "Q11": "Q21_1_2_000031",
//                            "Q12": "Q21_1_2_000032"
//                },
//                "Section C": {
//                    "Txt": "听对话，根据所听到的对话内容和提示词语，记录关键信息。对话读两遍。",
//                            "Sound": "Z1_B.mp3",
//                            "Q1": "Q21_1_3_000011",
//                            "Q2": "Q21_1_3_000012",
//                            "Q3": "Q21_1_3_000013",
//                            "Q4": "Q21_1_3_000014",
//                            "Q5": "Q21_1_3_000015"
//                }
//            }
//        }

        ExamSDK.d("Lesson init location: " + location + " id: " + lessonId + " obj: " + lessonObj);

        /*  examInOne/S13_1_0001.json  */
        this.location = location;
        /*  Lession1 */
        this.id = lessonId;
        this.position = Integer.valueOf(lessonId.replace(ID_PERFIX,""));

        JSONObject headObj = lessonObj.optJSONObject("Head");
        JSONObject bodyObj = lessonObj.optJSONObject("Body");

        this.name = headObj.optString("Name");
        //this.about = headObj.optString("About");
        this.testTime = headObj.optInt("TestTime");
        this.passScore = headObj.optInt("PassScore");
        this.difficulty = Difficulty.valueOf(headObj.optInt("Difficulty"));

        this.numQ = headObj.optInt("NumQ");

        JSONObject sectionsObject = lessonObj.optJSONObject("Sections");
        Character character = 65;
        String sectionName = "Section_" + character.toString();
        JSONObject sectionObj = null;
        while ((sectionObj = sectionsObject.optJSONObject(sectionName)) != null) {
            Section section = new Section(sectionName,sectionObj);
            sections.add(section);

            character++;
            sectionName = "Section_" + character.toString();
        }

        int index = 1;
        String value = null;
        while (!TextUtils.isEmpty(value = bodyObj.optString("Q" + index))) {
            qList.add(value);
            index++;
        }
    }

    public String getId() {
        return id;
    }

    public int getPosition() {
        return position;
    }

    public String getName() {
        return name;
    }

    public List<MediaItem> getAllMediaItem() {
        List<MediaItem> fileList = new ArrayList<MediaItem>();

        Set set = new HashSet();
        for (Subject subject : getSubjects()) {
            if (!set.contains(subject.getSection())) {
                set.add(subject.getSection());
                try {
                    fileList.addAll(subject.getSection().getAllMediaItem());
                } catch (NullPointerException e) {
                    Logger.e(">> nullpoint subject: " + subject);
                }
            }
            fileList.addAll(subject.getAllMediaItem());
        }
        return fileList;
    }

    public File getReplayMp3File() {
        return new File(ExamSDK.getPathStrategy().getRootPath(),ExamSDK.getPathStrategy().getFreeSubjectRelativePath(ExamSDK.FREE_DIR_NAME) + "/replay.mp3");
    }

    public List<Subject> getSubjects() {
        if (this.subjects == null) {
            this.subjects = new ArrayList<Subject>();

            for (int i = 0;i < qList.size();i++) {
                String value = qList.get(i);
                String fileName = value.substring(0,value.lastIndexOf("_")) + ".json";
                String subjectId = value.substring(value.lastIndexOf("_") + 1);

                File rootPath = ExamSDK.getPathStrategy().getRootPath();
                String location = ExamSDK.getPathStrategy().getSubjectRelativePath(String.valueOf(this.position));

                File file = new File(rootPath,location + "/" + fileName);

                JSONObject jsonObject = ExamUtil.getJSONObject(file);
                Logger.d("<< . jsonObject: " + jsonObject);
                JSONObject tObj = jsonObject.optJSONObject("T");
                Logger.d("<< . tObj: " + tObj);
                JSONObject subjectObj = tObj.optJSONObject(subjectId);
                String sectionName = subjectObj.optJSONObject("Head").optString("Section");
                Section section = getSectionByName(sectionName);
                Subject subject = new Subject(location,value,subjectId,section,subjectObj);
                this.subjects.add(subject);
            }

            qList = null;
        }
        return this.subjects;
    }

    private Section getSectionByName(String sectionName) {
        for (Section section : sections) {
            if (section.getName().equals(sectionName)) {
                return section;
            }
        }
        return null;
    }
}
